package com.dimeng.service;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.dimeng.R;
import com.dimeng.utils.FileUtilsByCCN;

/**
 * @author write by ccn<br>
 * <b>helloandroid100@gmail.com</b>
 * @version 0.1;2012-7-27 上午11:48:06<br>
 * descrition:
 */
public class DownloadService extends Service {
	private NotificationManager mNM;
	Notification notification;
	PendingIntent contentIntent;
	RemoteViews remoteViews;
    // Unique Identification Number for the Notification.
    // We use it on Notification start, and to cancel it.
	final int max = 100;
    private int NOTIFICATION = 1000;
    private Thread loadThread;

    /**
     * Class for clients to access.  Because we know this service always
     * runs in the same process as its clients, we don't need to deal with
     * IPC.
     */
    public class LocalBinder extends Binder {
        public DownloadService getService() {
            return DownloadService.this;
        }
    }

    @Override
    public void onCreate() {
    	mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        System.out.println("LocalService onCreate");
    }
    
    @Override
    public void onStart(Intent intent, int startId) {
    	Toast.makeText(this, "LocalService onStart", Toast.LENGTH_SHORT).show();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        System.out.println("LocalService onStartCommand");
        if(null != intent){
        	String httpUrl = intent.getStringExtra("url");
        	String saveFileNamePath = intent.getStringExtra("saveFileNamePath");
        	try {
				File saveFile = FileUtilsByCCN.createFile(saveFileNamePath);
				if(saveFile.exists()){
					showNotification(httpUrl,saveFile);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        // Cancel the persistent notification.
        mNM.cancel(NOTIFICATION);
        System.out.println("LocalService onDestroy");
        // Tell the user we stopped.
        Toast.makeText(this, "LocalService onDestroy", Toast.LENGTH_SHORT).show();
    }

    @Override
    public IBinder onBind(Intent intent) {
    	Toast.makeText(this, "LocalService onBind", Toast.LENGTH_SHORT).show();
        return mBinder;
    }
    
    @Override
    public boolean onUnbind(Intent intent) {
    	Toast.makeText(this, "LocalService onUnbind", Toast.LENGTH_SHORT).show();
    	return super.onUnbind(intent);
    }

    // This is the object that receives interactions from clients.  See
    // RemoteService for a more complete example.
    private final IBinder mBinder = new LocalBinder();

    /**
     * Show a notification while this service is running.
     */
    private void showNotification(String httpUrl,File file) {
        // Set the icon, scrolling text and timestamp
    	Intent intent = new Intent(Intent.ACTION_VIEW);  
        intent.setDataAndType(Uri.fromFile(file),"application/vnd.android.package-archive"); 
        
        notification = new Notification(R.drawable.favicon, "正在下载淘金地应用程序更新包", System.currentTimeMillis());
        contentIntent = PendingIntent.getActivity(this, NOTIFICATION,new Intent(), PendingIntent.FLAG_CANCEL_CURRENT);
        notification.setLatestEventInfo(this, "淘金地", "正在下载更新", contentIntent);
        remoteViews = new RemoteViews(this.getPackageName(),R.layout.progressbar);
        remoteViews.setProgressBar(R.id.pbId, max, 0, false);
        remoteViews.setTextViewText(R.id.percentNumId, "0");
        notification.contentView = remoteViews;
        mNM.notify(NOTIFICATION, notification);
        try {
			Thread.sleep(1000);//睡眠一秒，好让notification能及时显示出来
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
        if(null == loadThread || !loadThread.isAlive()){
        	Runnable r = new LoadThread(httpUrl,file);
        	loadThread = new Thread(r);
        	loadThread.start();
        }
    }
    
    class LoadThread implements Runnable{
    	String httpUrl;
    	File file;
    	
    	int process = 0;
    	LoadThread(String httpUrl,File file){
    		this.httpUrl = httpUrl;
    		this.file = file;
    	}
    	
		public void run() {
			double loadedLoad = 0;
			double contentLength = 0;
			OutputStream out = null;
			InputStream in = null;
			try {
				out = new FileOutputStream(file);
				URL url = new URL(httpUrl);
				URLConnection conn = url.openConnection();
				conn.setConnectTimeout(2000);
				conn.connect();
				contentLength = conn.getContentLength();
				in = conn.getInputStream();
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
			} catch (MalformedURLException e1) {
				e1.printStackTrace();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			
			try {
				int len = -1;
				int i = 0;
				byte[] buffer = new byte[1024 * 4];
				while(-1 != (len=in.read(buffer,0,buffer.length))){
					out.write(buffer, 0, len);
					loadedLoad += len;
					double percent = (loadedLoad/contentLength) * 100;
					process = (int) percent;
					if(loadedLoad == contentLength) {
						process = max;
						
						Intent intent = new Intent(Intent.ACTION_VIEW);  
				        intent.setDataAndType(Uri.fromFile(file),"application/vnd.android.package-archive"); 
						
						remoteViews.setTextViewText(R.id.downloadProgressLabelId, "下载完成,点击安装更新 ");
						notification = new Notification(R.drawable.favicon, "正在下载淘金地应用程序更新包", System.currentTimeMillis());
				        contentIntent = PendingIntent.getActivity(DownloadService.this, NOTIFICATION,intent, PendingIntent.FLAG_CANCEL_CURRENT);
				        notification.setLatestEventInfo(DownloadService.this, "淘金地", "淘金地应用更新下载完成,点击安装", contentIntent);
					}
			        if(++i %10 == 0 || loadedLoad == contentLength){
			        	remoteViews.setProgressBar(R.id.pbId, max, process, false);
			        	remoteViews.setTextViewText(R.id.percentNumId, process+"");
			        	notification.contentView = remoteViews;
			        	mNM.notify(NOTIFICATION, notification);
			        }
				}
				out.flush();
				out.close();
				in.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
    }
}
